﻿using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Cmd;
using GameData;
using UnityEngine.UI;

public class PickUI : MonoBehaviour
{

    public GameObject Content;
    public GameObject chouContent;
    public GameObject preNumPick;
    public List<NumPick> NumPicks = new List<NumPick>();
    public GameObject backBtn;

    //Pre
    public GameObject preNumInfo;

    //chou 
    public GameObject StartBtn;
    public bool isDoing = false;
    public bool isshowing = false;

    public Transform startText;
    public Transform ingText;
    public Transform topText;

    public GameObject textBtn;
    public Transform TeststartText;
    public Transform TestingText;
    public Transform TesttopText;
    public Text NumText;
    public string preGroupname ;

    public GameObject tipConObj;

    // Use this for initialization
    void Start()
    {
        
        //
        Screen.sleepTimeout = SleepTimeout.NeverSleep;
        Cmd.ReceiveCountSend rcs = new ReceiveCountSend();
        rcs.Send(GlobalVO.GetInstance().roleInfo.UserInfo, OnNumberInfo);
        Messenger<PickNumInfo>.AddListener("SC抽号", OnPickNumResponse);
        //Messenger<NumAllInfo>.AddListener("SC统计数据", OnrespmNumberInfo);
        Messenger.AddListener("SC队列信息", OnUpPickNumQue);
        Messenger<bool>.AddListener("移动完成", OnRunComplete);
        Messenger.AddListener("重连服务器", OnReConnect);


        EventTriggerListener.Get(backBtn).onClick = OnBack;
        EventTriggerListener.Get(StartBtn).onClick = OnStartBtn;

        EventTriggerListener.Get(textBtn).onClick = OnTestBtn;


        //获取抽号信息
    //    PickAllInfoSend pickAllInfoSend = new PickAllInfoSend();
      //  pickAllInfoSend.Send(GlobalVO.GetInstance().roleInfo.UserInfo, OnSendInfoResponse);
        SetState(0);
        SetTestState(0);
        isDoing = false;

        if (GlobalVO.GetInstance().SettingVo!=null)
        {
            textBtn.SetActive(GlobalVO.GetInstance().SettingVo.isuserTestBtn);

        }
        if (GlobalVO.GetInstance().NumAllInfo != null &&GlobalVO.GetInstance().NumAllInfo.SetDataDic!= null && GlobalVO.GetInstance().NumAllInfo.SetDataDic.ContainsKey("批次"))
        {
            preGroupname = GlobalVO.GetInstance().NumAllInfo.SetDataDic["批次"];
        }
        //


    }

    public void OnReConnect()
    {

        resStatr();

    }

    public void SetTestState(int indx)
    {
        if (indx == 0)
        {
            TeststartText.gameObject.SetActive(true);
            TestingText.gameObject.SetActive(false);
            TesttopText.gameObject.SetActive(false);
        }
        else if (indx == 1)
        {
            TeststartText.gameObject.SetActive(false);
            TestingText.gameObject.SetActive(true);
            TesttopText.gameObject.SetActive(false);
        }
        else if (indx == 2)
        {
            TeststartText.gameObject.SetActive(false);
            TestingText.gameObject.SetActive(false);
            TesttopText.gameObject.SetActive(true);
        }
    }


    public void SetState(int indx)
    {
        if (indx==0)
        {
            startText.gameObject.SetActive(true);
            ingText.gameObject.SetActive(false);
            topText.gameObject.SetActive(false);
        }
        else if (indx == 1)
        {
            startText.gameObject.SetActive(false);
            ingText.gameObject.SetActive(true);
            topText.gameObject.SetActive(false);
        }
        else if (indx == 2)
        {
            startText.gameObject.SetActive(false);
            ingText.gameObject.SetActive(false);
            topText.gameObject.SetActive(true);
        }
    }

    //
    void OnDestory()
    {
        Debug.Log("==================跳转了");
    }



    /// <summary>
    /// 
    /// </summary>
    /// <param name="obj"></param>
    void OnTestBtn(GameObject obj)
    {
        if (isDoing)
        {
            //正在抽奖中
            //
            if (!isshowing)
            {
                int ncount = pickNumInfo.NumberInfoList.Count;
                for (int i = 0; i < ncount; i++)
                {
                    NumPick np = NumPicks[i];
                    np.gameObject.SetActive(true);
                    np.Stop();
                }
                isshowing = true;
            }

            return;
        }
        //
        PickNumInfo testpickNumInfo = new PickNumInfo();
        testpickNumInfo.NumberInfoList = new List<NumberInfo>();
        List<NumberInfo> tespick = new List<NumberInfo>();
        int conts = GlobalVO.GetInstance().NumAllInfo.CurCount;
        if (conts< GlobalVO.GetInstance().NumAllInfo.PickNum)
        {
            conts = 20;
        }
        for (int i = 0; i < conts; i++)
        {
            NumberInfo nu = new NumberInfo();
            nu.value = i + 1;
            tespick.Add(nu);
        }
        //
        tespick = NumPick.GetRandomList(tespick);
        for (int i = 0; i < GlobalVO.GetInstance().NumAllInfo.PickNum; i++)
        {
            testpickNumInfo.NumberInfoList.Add(tespick[i]);
        }
        pickNumInfo = testpickNumInfo;
        OnPickNumResponse(testpickNumInfo);
        isDoing = true;
        isshowing = false;
      //  textBtn.gameObject.SetActive(false);
        SetTestState(2);
    }




    void OnStartBtn(GameObject obj)
    {

        if (GlobalVO.GetInstance().NumAllInfo.SetDataDic["开始抽号"]!="是")
        {
            return;
        }

        //判断是否已经完成
        if (GlobalVO.GetInstance().PickNumInfo!= null)
        {
            if (GlobalVO.GetInstance().PickNumInfo.isComplete==1)
            {
                //
                tipConObj.SetActive(true);
                //
                return;
            }
        }

        if (isDoing)
        {
            //正在抽奖中
            //
            if (!isshowing)
            {
                int ncount = pickNumInfo.NumberInfoList.Count;
                for (int i = 0; i < ncount; i++)
                {
                    NumPick np = NumPicks[i];
                    np.gameObject.SetActive(true);
                    np.Stop();
                }
                isshowing = true;
            }

            return;
        }
        isDoing = true;
        isshowing = true;
        PickNumSend pickNumSend = new PickNumSend();
        pickNumSend.Send(GlobalVO.GetInstance().roleInfo.UserInfo, OnClickPickNum);

        preGroupname = GlobalVO.GetInstance().NumAllInfo.SetDataDic["批次"];

        Button btn = textBtn.GetComponent<Button>();
        textBtn.gameObject.SetActive(false);
    }

    public void OnClickPickNum(PickNumInfo pickNumInfo)
    {

        GlobalVO.GetInstance().PickNumInfo = pickNumInfo;
        //
        //获取抽号
        //
        if (pickNumInfo.AllPickNumberList.Count<=0)
        {
            return;
        }
       

        int fcount = pickNumInfo.curIndex * GlobalVO.GetInstance().NumAllInfo.PickNum;
        int start = (pickNumInfo.curIndex -1)* GlobalVO.GetInstance().NumAllInfo.PickNum;
        for (int i = start; i < fcount; i++)
        {
            NumberInfo nf = new NumberInfo();
            if (i< pickNumInfo.AllPickNumberList.Count)
            {
                nf.value = pickNumInfo.AllPickNumberList[i];
                nf.QueueNum =  (i+1);
                pickNumInfo.NumberInfoList.Add(nf);
            }
        }

        OnPickNumResponse(pickNumInfo);
    }

    void OnBack(GameObject obj)
    {
        OnRemoveListener();

        Application.LoadLevel("Main");

    }

    public void OnRemoveListener()
    {
        Messenger.RemoveListener("重连服务器", OnReConnect);

        Messenger<PickNumInfo>.RemoveListener("SC抽号", OnPickNumResponse);
        Messenger<bool>.RemoveListener("移动完成", OnRunComplete);
        Messenger<NumAllInfo>.RemoveListener("SC统计数据", OnrespmNumberInfo);
        Messenger.RemoveListener("SC队列信息", OnUpPickNumQue);
    }


    void OnUpPickNumQue()
    {
        UpdatePickView();
    }

    void OnNumberInfo(NumAllInfo numallInfo)
    {

        GlobalVO.GetInstance().NumAllInfo = numallInfo;
        
        int chouNum = GlobalVO.GetInstance().NumAllInfo.PickNum;
        Debug.Log("生成" + chouNum);
        for (int i = 0; i < chouNum; i++)
        {
            GameObject obj = GameObject.Instantiate(preNumPick);
            obj.transform.SetParent(chouContent.transform, false);
            NumPick numPick = obj.GetComponent<NumPick>();
            numPick.Index = i;
            NumPicks.Add(numPick);
        }
        GetPickNum gp = new GetPickNum();
        DataInfo di = new DataInfo();
        di.valueStr = "";
        gp.Send(di, InitPickNum);

    }

    void InitPickNum(PickNumInfo pn)
    {
        GlobalVO.GetInstance().PickNumInfo = pickNumInfo;
        pickNumInfo = pn;
        UpdatePickView();
    }


    void UpdateNum()
    {
        if (GlobalVO.GetInstance().PickNumInfo != null)
        {
            //设置剩余数量
            int dcount = GlobalVO.GetInstance().PickNumInfo.AllPickNumberList.Count;
            int needt = dcount / GlobalVO.GetInstance().NumAllInfo.PickNum;
            if (GlobalVO.GetInstance().PickNumInfo == null)
            {
                needt = needt - 0;
            }
            else
            {
                needt = needt - GlobalVO.GetInstance().PickNumInfo.curIndex;
            }
            NumText.text = "剩余抽奖次数:" + needt;
        }
    }


    void OnrespmNumberInfo(NumAllInfo numallInfo)
    {
        UpdatePickView();
        //
    }


    private PickNumInfo pickNumInfo;



    public void OnPickNumResponse(PickNumInfo pick)
    {
        if (pick.isComplete==1)
        {
            resStatr();
            return;
        }


        if (pick.NumberInfoList.Count<=0)
        {
            resStatr();
            return;
        }
        pickNumInfo = pick;
        SetState(2);
        isDoing = true;
        isshowing = false;
        List<int> picknu = new List<int>();
        for (int i = 0; i < pick.NumberInfoList.Count; i++)
        {
            picknu.Add(pick.NumberInfoList[i].value);
        }

        for (int i = 0; i < NumPicks.Count; i++)
        {
            NumPicks[i].gameObject.SetActive(false);
            NumPicks[i].StartText.text = "";
        }
        int ncount = pick.NumberInfoList.Count;
        for (int i = 0; i < ncount; i++)
        {
            NumPick np = NumPicks[i];
            np.pickNum = picknu;
            np.gameObject.SetActive(true);
            NumberInfo numberInfo = pick.NumberInfoList[i];
            np.EndNum = numberInfo.value;
            np.SetTextNum();
            if (i==ncount-1)
            {
                np.isComMessage = true;
            }

            np.TimeRun();
        }
        //


        //
    }

    private void onstopShow(PickNumInfo pick)
    {

    }

    /// <summary>
    /// 动画完成
    /// </summary>
    public void OnRunComplete(bool iscom)
    {
        //更新数据
        //弹出恭喜界面
        Debug.Log("获取到消息");

        Invoke("resStatr", 1);
        //

        UpdatePickView();
    }

    public void resStatr()
    {
        isDoing = false;
        isshowing = false;
        SetTestState(0);
        SetState(0);

    }


    public void OnSendInfoResponse(PickAllNumInfo pickAllNumInfo)
    {
        GlobalVO.GetInstance().PickAllNumInfo = pickAllNumInfo;

        UpdatePickView();

    }

    public void UpdatePickView()
    {
        UpdateNum();
        if (GlobalVO.GetInstance().NumAllInfo==null|| pickNumInfo==null)
        {
            return;
        }
        //
        List<NumberInfo> rec = new List<NumberInfo>();
        int fcount = pickNumInfo.curIndex * GlobalVO.GetInstance().NumAllInfo.PickNum;
        int start = (pickNumInfo.curIndex - 1) * GlobalVO.GetInstance().NumAllInfo.PickNum;
        for (int i = 0; i < fcount; i++)
        {
            NumberInfo nf = new NumberInfo();
            if (i < pickNumInfo.AllPickNumberList.Count)
            {
                nf.value = pickNumInfo.AllPickNumberList[i];
                nf.QueueNum = (i + 1);
                rec.Add(nf);
            }
        }


        int childCount = Content.transform.childCount;
        int numCount = rec.Count;
        int vnck = Math.Max(childCount, numCount);
        for (int i = 0; i < vnck; i++)
        {
            if (i < numCount)
            {
                Text text;
                if (i < childCount)
                {
                    Transform objtf = Content.transform.GetChild(i);
                    objtf.gameObject.SetActive(true);
                    text = objtf.FindChild("Text").GetComponent<Text>();

                }
                else
                {
                    GameObject obj = GameObject.Instantiate(preNumInfo);
                    obj.transform.SetParent(Content.transform);
                    obj.transform.SetAsLastSibling();
                   

                    text = obj.transform.FindChild("Text").GetComponent<Text>();
                }
                //
                NumberInfo numberInfo = rec[i];
                text.text = "第"+ numberInfo.QueueNum+"位：" + UtilTool.getNumbertoStr(numberInfo.value)  + "号" ;
            }
            else
            {
                Transform objtf = Content.transform.GetChild(i);
                objtf.gameObject.SetActive(false);

            }

        }
        //resize
        ReSize();
    }

    public GridLayoutGroup GridLayoutGroup;


    public void ReSize()
    {
        int num = 0;
        for (int i = 0; i < Content.transform.childCount; i++)
        {
            RectTransform rect = Content.transform.GetChild(i).GetComponent<RectTransform>();
            if (rect.gameObject.activeSelf)
            {
                num++;
            }


        }
        RectTransform contRect = Content.GetComponent<RectTransform>();
        float dy = num * (GridLayoutGroup.cellSize.y + GridLayoutGroup.spacing.y) / 5;


        contRect.sizeDelta = new Vector2(contRect.rect.width, dy);
    }

    //
    public void OnRunPick()
    {
        


    }
	
	// Update is called once per frame
	void Update () {
	
	}
}
